# Echo Client
# 
# @see http://pymotw.com/2/socket/tcp.html
# 
# The client program sets up its socket differently from the way a server does. 
# Instead of binding to a port and listening, 
# it uses connect() to attach the socket directly to the remote address.

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening
server_address = ('localhost', 3333)
print( 'connecting to', server_address, file=sys.stderr )
sock.connect(server_address)

# After the connection is established, data can be sent through the socket
# with sendall() and received with recv(), just as in the server.
try:
    # Send data
    message = 'This is the message.  It will be repeated.'
    print( 'sending:', message, file=sys.stderr )
    sock.sendall(message.encode('utf-8'))

    # Look for the response
    amount_received = 0
    amount_expected = len(message)
    
    while amount_received < amount_expected:
        data = sock.recv(256)
        amount_received += len(data)
        print( 'received:', data, file=sys.stderr )

finally:
    print( 'closing socket', file=sys.stderr )
    sock.close()

# When the entire message is sent and a copy received, the socket is closed to free up the port.
